﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GuildStock.Services;

namespace GuildStock.Models
{
  /// <summary>
  /// Guild data class. Encapsulates business logic for the class.
  /// </summary>
  public partial class Guild
  {
    /// <summary>
    /// Gets the list of guilds ranked for the realm.
    /// If realm is null the list returns all all guilds ranked.
    /// </summary>
    /// <param name="realm">Realm name.</param>
    /// <returns>List of guilds.</returns>
    public static IEnumerable<Guild> GetRankedList(string realm, int maxNum)
    {
      var context = new GuildStockDataDataContext();

      var guildQuery = string.IsNullOrEmpty(realm) 
        ? context.Guilds 
        : context.Guilds.Where(g => g.RealmName == realm);

      var guildList = guildQuery
        .OrderByDescending(guild => guild.Updated)
        .ToList()
        .Distinct(new GuildComparer())
        .OrderByDescending(g => g._Score)
        .Take(maxNum)
        .ToList();

      for (int index = 0; index < guildList.Count; index++)
      {
        guildList[index].Rank = index + 1;
      }

      return guildList;
    }
  }
}